import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import useTriggerOutset from "../../../../hooks/useClickOutset";

function Index(props: any, ref: any) {
  const atRootRef = useRef<HTMLDivElement | null>(null);
  const [atRootStyle, setAtRootStyle] = useState({
    left: 0,
    top: 0,
    open: false,
  });

  useTriggerOutset(
    () => {
      setAtRootStyle((prevState) => {
        return {
          ...prevState,
          open: false,
        };
      });
    },
    "click",
    ".at-wrapper",
    '.show-at-wrapper'
  );

  // 向外界暴漏出内容
  useImperativeHandle(ref, () => {
    return {
      setAtRootStyle,
    };
  });

  const handleSelectAt = (row: any) => {
    props.handleSelectAt?.({ id: Date.now(), name: row });
    setAtRootStyle((prevState) => {
      return {
        ...prevState,
        open: false,
      };
    });
  };
  return (
    <div
      ref={atRootRef}
      className="at-wrapper fixed z-20 w-[200px] h-[400px] bg-blue-400 rounded-lg translate-y-[-103%] select-none overflow-y-auto "
      style={{
        top: atRootStyle.top + "px",
        left: atRootStyle.left + "px",
        display: atRootStyle.open ? "" : "none",
      }}
    >
      <ul>
        {new Array(13).fill(1).map((one, index) => (
          <li
            key={index}
            className=" cursor-pointer h-[36px] leading-[36px] px-3 hover:bg-gray-500"
            onClick={() => handleSelectAt(index)}
          >
            {index}
          </li>
        ))}
      </ul>
    </div>
  );
}
export default forwardRef(Index);
